package com.ruoyi.web.controller.mes;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.web.domain.MesTakeVersion;
import com.ruoyi.web.domain.mes.MesUser;
import com.ruoyi.web.mapper.MesConfigMapper;
import com.ruoyi.web.mapper.MesMachineMapper;
import com.ruoyi.web.mapper.MesUserMapper;
import com.ruoyi.web.service.IMesUserService;
import com.ruoyi.web.domain.mes.MesWorkShop;
import com.ruoyi.web.service.MesMachineService;
import com.ruoyi.web.service.MesMachineUserService;
import com.ruoyi.web.service.ProduceProductService;
import com.ruoyi.web.vo.MesMachine;
import com.ruoyi.web.vo.MesMachineUser;
import com.ruoyi.web.vo.Produce;
import com.ruoyi.web.vo.ProduceProduct;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;


@RestController
@RequestMapping("/machine")
public class MesMachineController extends BaseController {
    @Resource
    private MesMachineService mesMachineService;

    @Resource
    private MesMachineUserService mesMachineUserService;

    @Resource
    private IMesUserService mesUserService;
    @Resource
    private MesConfigMapper configMapper;
    @Resource
    private MesMachineMapper mesMachineMapper;

    @Resource
    private MesUserMapper mesUserMapper;

    @PostMapping(value = "/list")
    public TableDataInfo list(@RequestBody Map<String, String> params) {
        startPage(params);
//        String initiationTime = params.get("initiationTime");
        String machineNo = params.get("machineNo");
        String machineName = params.get("machineName");
        String workshopId = params.get("workshopId");
        String type = params.get("type");
        String trimmingtype = params.get("trimmingType"); //白纸裁切类型
        String size = params.get("size");
        String model = params.get("model");
        String status = params.get("status");
        String workshopName = params.get("workshopName");
        String workshopNo = params.get("workshopNo");
        List<String> list =new ArrayList<>();
        if(StringUtils.isNotEmpty(type) && type.contains(",")) {
            list = Arrays.asList(type.split(","));
        }
        MesMachine machine = new MesMachine();
        machine.setParams(params);
        List<MesMachine> mesMachines = mesMachineService.list(new QueryWrapper<MesMachine>().lambda()
                .eq(StringUtils.isNotEmpty(machineNo), MesMachine::getMachineNo, machineNo)
                .like(StringUtils.isNotEmpty(machineName), MesMachine::getMachineName, machineName)
                .like(StringUtils.isNotEmpty(workshopName), MesMachine::getWorkshopName, workshopName)
                .like(StringUtils.isNotEmpty(workshopNo), MesMachine::getWorkshopNo, workshopNo)
                .eq(StringUtils.isNotEmpty(workshopId), MesMachine::getWorkshopId, workshopId)
                .eq(StringUtils.isNotEmpty(status), MesMachine::getStatus, status)
                .eq(StringUtils.isNotEmpty(size), MesMachine::getSize, size)
                .eq(StringUtils.isNotEmpty(model), MesMachine::getModel, model)

                .eq(StringUtils.isNotEmpty(type) && !type.contains(","), MesMachine::getType, type)
                .in(StringUtils.isNotEmpty(list), MesMachine::getType, list)
                //.or().eq(StringUtils.isNotEmpty(trimmingtype), MesMachine::getType, trimmingtype)
                .orderByDesc(MesMachine::getCreateTime)
        );
        for (MesMachine mesMachine : mesMachines) {
            List<MesMachineUser> mesMachineUserList = mesMachineUserService.list(new QueryWrapper<MesMachineUser>()
                    .lambda()
                    .eq(MesMachineUser::getMachineId, mesMachine.getPid()));
            String headUserName="";
            String headUserPhone="";
            for (MesMachineUser user : mesMachineUserList) {
                if (user.getUserId() != null && user.getUserId() != 0) {
                    MesUser info = mesUserService.selectMesUserById(user.getUserId());
                    if(StringUtils.isNotEmpty(user.getPosition())&&user.getPosition().equals("1") && info!=null){
                        headUserName=headUserName + info.getName()+",";
                        headUserPhone=headUserPhone + info.getTelephone()+",";
                    }
                    user.setMesUsers(info);
                }
            }
            headUserName=StringUtils.isNotEmpty(headUserName)?headUserName.substring(0, headUserName.length() - 1):"";
            headUserPhone=StringUtils.isNotEmpty(headUserPhone)?headUserPhone.substring(0, headUserPhone.length() - 1):"";
            mesMachine.setHeadUserName(headUserName);
            mesMachine.setHeadUserPhone(headUserPhone);
            mesMachine.setMesMachineUserList(mesMachineUserList);
        }
        return getDataTable(mesMachines);
//        List<MesMachine> mesMachines=mesMachineMapper.selectMachineUserList(machine);
//       return  getDataTable(mesMachines);
    }


    @PostMapping(value = "/export")
    public AjaxResult export(@RequestBody Map<String, String> params) {
        String machineNo = params.get("machineNo");
        String machineName = params.get("machineName");
        String workshopId = params.get("workshopId");
        String type = params.get("type");
        List<MesMachine> list = mesMachineService.list(new QueryWrapper<MesMachine>().lambda()
                .like(StringUtils.isNotEmpty(machineNo), MesMachine::getMachineNo, machineNo)
                .like(StringUtils.isNotEmpty(machineName), MesMachine::getMachineName, machineName)
                .eq(StringUtils.isNotEmpty(workshopId), MesMachine::getWorkshopId, workshopId)
                .eq(StringUtils.isNotEmpty(type), MesMachine::getType, type)
                .orderByDesc(MesMachine::getCreateTime));
        ExcelUtil<MesMachine> util = new ExcelUtil<>(MesMachine.class);
        return util.exportExcel(list, "sheet1");
    }

    @PostMapping(value = "/add")
    public AjaxResult add(@RequestBody MesMachine mesMachine) {
        if (mesMachine.getPid() == null) {
            mesMachine.setPid(UUID.randomUUID().toString().replace("-", ""));

            Map<String, Object> map = new HashMap<>();
            map.put("columnName", "machine_no");
            map.put("tableName", "mes_machine_info");
            int maxNum = configMapper.getMouthMaxId(map);
            String code = PinYinUtils.getCodeNormal(maxNum, "SB");
            mesMachine.setMachineNo(code);//设备编号
            mesMachine.setCreateTime(new Date());
            mesMachine.setCreateUser(SecurityUtils.getUsername());
        } else {
            mesMachine.setUpdateTime(new Date());
        }
        if (mesMachine.getMesMachineUserList() != null && mesMachine.getMesMachineUserList().size() != 0) {
            mesMachine.getMesMachineUserList().forEach(e -> {
                e.setMachineId(mesMachine.getPid());
            });
        }
        mesMachineService.saveOrUpdate(mesMachine);

        mesMachineUserService.remove(new QueryWrapper<MesMachineUser>().lambda().eq(MesMachineUser::getMachineId, mesMachine.getPid()));
        if (mesMachine.getMesMachineUserList() != null && mesMachine.getMesMachineUserList().size() != 0) {
            mesMachineUserService.saveBatch(mesMachine.getMesMachineUserList());
        }
        return AjaxResult.success("添加成功", mesMachine.getPid());
    }

    @PostMapping(value = "/updatestatus")
    public AjaxResult updatestatus(@RequestBody MesMachine mesMachine) {
        mesMachineService.update(new UpdateWrapper<MesMachine>().lambda()
                .set(MesMachine::getStatus, mesMachine.getStatus()).eq(MesMachine::getPid, mesMachine.getPid()));
        return AjaxResult.success("操作成功", mesMachine.getPid());
    }

    @ApiOperation("查询当前登陆人的机台")
    @GetMapping("/getMachine")
    public TableDataInfo getMachine()
    {
        Long userId= SecurityUtils.getUserId();
        MesUser mesUser=mesUserMapper.selectMesUserBySysUserId(userId);
        List<MesMachine> list=new ArrayList<>();
        if(mesUser!=null && StringUtils.isNotEmpty(mesUser.getName())) {
            MesMachineUser user = new MesMachineUser();
            user.setUserId(mesUser.getId());
            list = mesMachineMapper.getMachine(user);
//        List<MesMachineUser> list = mesMachineUserService.list(new QueryWrapper<MesMachineUser>()
//                .lambda().eq(MesMachineUser::getUserId,UserId));
        }
        return getDataTable(list);
    }

    // @PostMapping(value = "/getById")
    @GetMapping(value = "/getById")
    public AjaxResult getById(MesMachine mesMachine) {  //@RequestBody Map<String, String> params
//        MesMachine machineFiter = mesMachineService.getOne(new QueryWrapper<MesMachine>().lambda()
//                .eq(StringUtils.isNotEmpty(mesMachine.getPid()), MesMachine::getPid, mesMachine.getPid())
//                .eq(StringUtils.isNotEmpty(mesMachine.getMachineNo()), MesMachine::getMachineNo, mesMachine.getMachineNo())
//        );
        mesMachine = mesMachineService.getById(mesMachine.getPid());
        List<MesMachineUser> mesMachineUserList = mesMachineUserService.list(new QueryWrapper<MesMachineUser>()
                .lambda()
                .eq(MesMachineUser::getMachineId, mesMachine.getPid()));
        for (MesMachineUser user : mesMachineUserList) {
            if (user.getUserId() != null && user.getUserId() != 0) {
                MesUser info = mesUserService.selectMesUserById(user.getUserId());
                user.setMesUsers(info);
            }
        }
        mesMachine.setMesMachineUserList(mesMachineUserList);
        return AjaxResult.success("查询成功", mesMachine);
    }

    @PostMapping(value = "/deleteById")
    public AjaxResult deleteById(@RequestBody Map<String, String> params) {
        mesMachineService.removeById(params.get("pid"));
        mesMachineUserService.remove(new QueryWrapper<MesMachineUser>().lambda().eq(MesMachineUser::getMachineId, params.get("pid")));
        return AjaxResult.success("删除成功");
    }

    //根据机台类型查询机台
    @PostMapping(value = "/getMachineType")
    public TableDataInfo getMachineType(@RequestBody Map<String, String> params) {
        startPage(params);
        String type = params.get("type");
        String machineNo = params.get("machineNo");
        String machineName = params.get("machineName");
        String workshopId = params.get("workshopId");

      List<MesMachine>  mesMachines=mesMachineService.list(new QueryWrapper<MesMachine>().lambda()
                .like(StringUtils.isNotEmpty(machineNo), MesMachine::getMachineNo, machineNo)
                .like(StringUtils.isNotEmpty(machineName), MesMachine::getMachineName, machineName)
                .eq(StringUtils.isNotEmpty(workshopId), MesMachine::getWorkshopId, workshopId)
                .eq(true, MesMachine::getStatus, 2)
                .eq(StringUtils.isNotEmpty(type), MesMachine::getType, type));
        for (MesMachine mesMachine : mesMachines) {
            List<MesMachineUser> mesMachineUserList = mesMachineUserService.list(new QueryWrapper<MesMachineUser>()
                    .lambda()
                    .eq(MesMachineUser::getMachineId, mesMachine.getPid()));
            String headUserName="";
            String headUserPhone="";
            for (MesMachineUser user : mesMachineUserList) {
                if (user.getUserId() != null && user.getUserId() != 0) {
                    MesUser info = mesUserService.selectMesUserById(user.getUserId());
                    if(StringUtils.isNotEmpty(user.getPosition())&&user.getPosition().equals("1") && info!=null){
                        headUserName=headUserName + info.getName()+",";
                        headUserPhone=headUserPhone + info.getTelephone()+",";
                    }
                    user.setMesUsers(info);
                }
            }
            headUserName=StringUtils.isNotEmpty(headUserName)?headUserName.substring(0, headUserName.length() - 1):"";
            headUserPhone=StringUtils.isNotEmpty(headUserPhone)?headUserPhone.substring(0, headUserPhone.length() - 1):"";
            mesMachine.setHeadUserName(headUserName);
            mesMachine.setHeadUserPhone(headUserPhone);
            mesMachine.setMesMachineUserList(mesMachineUserList);
        }
        return getDataTable(mesMachines);
    }

    @PostMapping(value = "/getMachineUser")
    public TableDataInfo getMachineUser(@RequestBody Map<String, String> params) {
        startPage(params);
        String id = params.get("id");
        String team = params.get("team");
        TableDataInfo list = getDataTable(mesMachineUserService.list(new QueryWrapper<MesMachineUser>().lambda()
                .eq(StringUtils.isNotEmpty(id), MesMachineUser::getMachineId, id)
                .eq(StringUtils.isNotEmpty(team), MesMachineUser::getTeam, team)
        ));
        return list;
    }

    // 修改是否分配内文生产单
    @PostMapping("/upIsFpnw")
    public AjaxResult upIsFpnw(@RequestBody MesMachine machine){
        if(StringUtils.isEmpty(machine.getPid()) || machine.getIsFpnw() == null){
            return AjaxResult.error("信息获取不完整");
        }
        mesMachineService.update(new UpdateWrapper<MesMachine>().set("is_fpnw", machine.getIsFpnw()).eq("pid", machine.getPid()));
        return AjaxResult.success();
    }
}



